<template>
  <CardDialog v-model:visible="show" width="100vw" :title="`${backType === 'image' ? '图片' : '视频'}回放`" @close="close">
    <div class="play-back">
      <div class="play-content" v-if="show">
        <MapCard ref="mapRef" :alarmInfo="alarmInfo" />
        <ImageList ref="imageRef" :alarmInfo="alarmInfo" v-if="backType === 'image'" />
        <VideoList ref="videoRef" :alarmInfo="alarmInfo" v-if="backType === 'video'" />
      </div>
      <div class="play-bottom">
        <ProgressBar ref="ProgressRef" @updateTime="updateTime" />
      </div>
    </div>
  </CardDialog>
</template>

<script setup>
  import { ref } from 'vue';
  import CardDialog from '/@/components/cardDialog/index.vue';
  import ProgressBar from './progressBar.vue';
  import MapCard from './map.vue';
  import { api as fusionTrackApi } from '/@/api/plat/fusion-track.js';
  import ImageList from './image.vue';
  import VideoList from './video.vue';

  let trackList = [];
  let firstPlay = true;

  const show = ref(false);
  const ProgressRef = ref();
  const mapRef = ref();
  const imageRef = ref();
  const videoRef = ref();
  const backType = ref('');
  const alarmInfo = ref({});

  function open(row, type) {
    alarmInfo.value = row;
    backType.value = type;
    show.value = true;
    fusionTrackApi.queryList({ targetId: row.targetId, startTime: row.startTime, endTime: row.endTime }).then(({ data }) => {
      trackList = data.reverse();
      ProgressRef.value.initProgress({
        startTime: row.startTime,
        endTime: row.endTime,
      });
      if (backType.value === 'image') {
        imageRef.value.getImages(row);
      } else {
        videoRef.value.getVideoList(row);
      }
    });
  }

  /**
   *
   * @param time
   * @param type active: 点击或拖动进度条 passive: 定时任务
   */
  function updateTime(time, type) {
    let index = 0;
    for (let i = 0; i < trackList.length; ++i) {
      if (+new Date(time) < +new Date(trackList[i].dataTime)) {
        if (i !== 0) {
          index = i;
          break;
        }
      }
      index = trackList.length;
    }
    const list = trackList.slice(0, index).map((m) => [m.longitude, m.latitude, m.course]);
    mapRef.value.startPlay(list);
    if (firstPlay) {
      firstPlay = false;
      mapRef.value.moveToStartPoint(trackList[0]);
    }
    if (backType.value === 'image') {
      // 图片渲染
      imageRef.value.playCamera(time);
    } else {
      // 视频跳转
      if (type === 'active') {
        videoRef.value.restartPlay(time);
      }
    }
  }

  function close() {
    ProgressRef.value.end();
    backType.value = '';
    firstPlay = true;
  }

  defineExpose({ open });
</script>

<style lang="less" scoped>
  .play-back {
    width: 100%;
    .play-content {
      width: 100%;
      height: calc(100vh - 120px);
      display: flex;
      justify-content: space-between;
      position: relative;
    }
  }
  .card-dialog {
    top: 0;
    height: 100vh;
  }
</style>
